package com.hyk.commonLib.common.fragment;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;

import com.dylanc.activityresult.launcher.StartActivityLauncher;
import com.dylanc.viewbinding.base.ViewBindingUtil;
import com.hjq.permissions.XXPermissions;
import com.hyk.commonLib.common.entity.ReqPermissionResult;
import com.hyk.commonLib.common.utils.BusUtils;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.android.FragmentEvent;
import com.trello.rxlifecycle4.components.support.RxFragment;

import io.reactivex.rxjava3.core.Observable;
import lombok.Getter;

/**
 * Created by 贺玉琨 on 2019/3/7 0007.
 */
public abstract class BaseFragment<DATA_BINDING extends ViewDataBinding> extends RxFragment {
    public final StartActivityLauncher startActivityLauncher = new StartActivityLauncher(this);
    @Getter
    protected DATA_BINDING dataBinding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = ViewBindingUtil.inflateWithGeneric(this, getLayoutInflater(), container, false);
        dataBinding.setLifecycleOwner(this);
        BusUtils.register(this);
        return dataBinding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        dataBinding = null;
    }

    @Override
    public void onDestroy() {
        BusUtils.unregister(this);
        super.onDestroy();
    }

    public <T> LifecycleTransformer<T> bindUntilDestroy() {
        return bindUntilEvent(FragmentEvent.DESTROY);
    }

    public Observable<ReqPermissionResult> requestPermissions(String... permissions) {
        return Observable.create(emitter -> XXPermissions.with(BaseFragment.this)
                .permission(permissions)
                .request((permissions1, all) -> {
                    ReqPermissionResult reqPermissionResult;
                    if (all) {
                        reqPermissionResult = ReqPermissionResult.success(permissions1);
                    } else {
                        boolean isPermanentDenied = XXPermissions.isPermanentDenied(getActivity(), permissions1);
                        reqPermissionResult = ReqPermissionResult.fail(permissions1, isPermanentDenied);
                    }
                    emitter.onNext(reqPermissionResult);
                }));
    }

    /**
     * @param keyCode
     * @param event
     * @return true 已处理，activity不再处理；false 未处理
     */
    public boolean onBackPress(int keyCode, KeyEvent event) {
        return true;
    }
}
